﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Infrastructure.Entities;
using GoodMan.Infrastructure.Entities.Repository;
using System.Data.SqlClient;
using System.Data;

namespace GoodMan.Portal.Biz
{
    public class SpecialSaleBiz
    {
        public static bool SaveSpecialSale(SpecialSale specialSale,Policy policy)
        {
            var specialSaleTemp = new SpecialSale().Find(c => c.ProductId == specialSale.ProductId);
            if (specialSaleTemp == null)
            {
                specialSale.PostAdd();
            }
            //执行价格策略的保存
            policy.PostAdd();
            return true;
        }

        public static ItemListBox<Product> GetAllSpecialProducts(string productkey, int page, int pagesize)
        {
            //var count = new Product().Count(c => (c.ProductType == categoryId || categoryId == 0) && (c.ProductSubType == subcategoryId || subcategoryId == 0) && (c.ProductName.Contains(productkey) || c.ProductCode.Contains(productkey)));
            var count = 0;
            using (Context ctx = new Context())
            {
                count = (from c in ctx.Product
                             join d in ctx.SpecialSale
                             on c.Id equals d.ProductId
                             where c.ProductName.Contains(productkey) || c.ProductCode.Contains(productkey)
                             select new { c, d }).Count();
            }
            using(Context ctx=new Context())
            {
                string sql = @"select top (@pagesize) t.* from (select ROW_NUMBER() OVER (ORDER BY a.createdate desc) AS RowNumber, a.*,d.Price as DefaulSalePrice from dbo.T_Product a
                            inner join dbo.T_SpecialSale b on a.Id=b.ProductId
                            inner join (select * from dbo.T_Policy c where c.PolicyType=1) d 
                             on a.Id=d.ProductId 
                            where a.areacode=1 and a.ProductCode like '%'+@productkey+'%' or a.ProductName like '%'+@productkey+'%') t
                            where t.RowNumber>@pagesize*@page";

                var datatable = ctx.ExcuteSQL(sql,
                     new SqlParameter("@productkey", productkey),
                      new SqlParameter("@pagesize", pagesize),
                     new SqlParameter("@page", page)
                    );

                List<Product> data = null;
                if (datatable != null && datatable.Rows.Count > 0)
                {
                     var datetime=DateTime.Now;
                    data = new List<Product>();
                    foreach (DataRow row in datatable.Rows)
                    {
                        var product = new Product()
                        {
                            CreateDate = Convert.ToDateTime(row["CreateDate"].ToString()),
                            Id = int.Parse(row["Id"].ToString()),
                            Images = (row["Images"].ToString() != null&&row["Images"].ToString() !="") ? row["Images"].ToString().Split(';')[0] : "",
                            ProductCode = row["ProductCode"].ToString(),
                            ProductName = row["ProductName"].ToString(),
                            PurchasePrice = decimal.Parse(row["PurchasePrice"] != null ? row["PurchasePrice"].ToString() : "0"),
                            DefaulSalePrice = decimal.Parse(row["DefaulSalePrice"] != null ? row["DefaulSalePrice"].ToString() : "0")
                        };
                       
                        var policys = new Policy().FindAll(c => c.ProductId == product.Id && c.PolicyType == 2 && c.IsActive == true);
                        var policy = (from c in policys
                                      where c.StartDate < datetime && c.ExpireDate > datetime
                                      select c).FirstOrDefault();
                        if (policy != null)
                        {
                            product.PolicyPrice = policy.Price;
                            product.StartDate = policy.StartDate.ToString("yyyy-MM-dd HH:mm:ss");
                            product.EndDate = policy.ExpireDate.ToString("yyyy-MM-dd HH:mm:ss");
                            product.StateStr = "进行中";
                        }
                        else
                        {
                            policy = (from c in policys
                                      where c.StartDate > datetime
                                      select c).FirstOrDefault();
                            if (policy != null)
                            {
                                product.PolicyPrice = policy.Price;
                                product.StartDate = policy.StartDate.ToString("yyyy-MM-dd HH:mm:ss");
                                product.EndDate = policy.ExpireDate.ToString("yyyy-MM-dd HH:mm:ss");
                                product.StateStr = "等待中";
                            }
                            else
                            {
                                policy = (from c in policys
                                          where c.ExpireDate < datetime
                                          select c).FirstOrDefault();
                                if (policy != null)
                                {
                                    product.PolicyPrice = policy.Price;
                                    product.StartDate = policy.StartDate.ToString("yyyy-MM-dd HH:mm:ss");
                                    product.EndDate = policy.ExpireDate.ToString("yyyy-MM-dd HH:mm:ss");
                                    product.StateStr = "已过期";
                                }
                                 
                            }
                        }
                        
                        data.Add(product);
                    }
                }
                var list = new ItemListBox<Product>(data).BuildPage(
                    count, page, pagesize, new PageParameter() { Style = "workspace" });
                return list;
            }

        }

        public static bool DelSpecialSale(int productid)
        {
            try
            {
                using (Context ctx = new Context())
                {
                    ctx.Delete<T_SpecialSale>()
                        .WhereSet(c => c.ProductId, WhereOperator.Equal, productid)
                        .End()
                        .Excute();
                }

                return true;
            }
            catch (Exception ex)
            {
                //日志记录
                return false;
            }
            return false;
        }

        
    }
}
